<!DOCTYPE html>
<html>

<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>商品编辑</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
  
    <link rel="stylesheet" href="/plugins/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="/plugins/adminLTE/css/AdminLTE.css">
    <link rel="stylesheet" href="/plugins/adminLTE/css/skins/_all-skins.min.css">
    <link rel="stylesheet" href="/css/style.css">
	<script src="/plugins/jQuery/jquery-2.2.3.min.js"></script>
    <script src="/plugins/bootstrap/js/bootstrap.min.js"></script>
    
    <!-- 富文本编辑器 -->
	<link rel="stylesheet" href="/plugins/kindeditor/themes/default/default.css" />
	<script charset="utf-8" src="/plugins/kindeditor/kindeditor-min.js"></script>
	<script charset="utf-8" src="/plugins/kindeditor/lang/zh_CN.js"></script>
    
    
      
    <script>
		$(function () {
			listItemCat(0)
		})
		function listItemCat(parentId) {
			$.post("/itemCat/listItemCat",{parentId:parentId},function (result) {
				let str='<option value="-1">请选择</option>'
				$(result.data).each(function (i,e) {
					str+='<option value="'+e.id+'">'+e.name+'</option>'
				})
				$("#category1Id").html(str)
			})

		}
		function listItemCat2(parentId) {
			$.post("/itemCat/listItemCat",{parentId:parentId},function (result) {
				let str='<option value="-1">请选择</option>'
				$(result.data).each(function (i,e) {
					str+='<option value="'+e.id+'">'+e.name+'</option>'
				})
				$("#category2Id").html(str)
			})

		}
		function listItemCat3(parentId) {
			$.post("/itemCat/listItemCat",{parentId:parentId},function (result) {
				let str='<option value="-1">请选择</option>'
				$(result.data).each(function (i,e) {
					str+='<option value="'+e.id+'">'+e.name+'</option>'
				})
				$("#category3Id").html(str)

			})

		}
		function getType(id) {
			let typeId = ''
			$.ajax({
				url:"/itemCat/getItemCat",
				type:"post",
				dataType:"json",
				data:{id:id},
				async:false,
				success:function (result) {
					$("#typeId").html("模板ID:"+result.info.typeId)
					typeId = result.info.typeId
				}
			})
			getTypeTemplate(typeId)
			getSpec(typeId)
		}
		function getTypeTemplate(typeId) {
			$.post("/typeTemplate/getTypeTemplate",{id:typeId},function (result) {
				let parse = JSON.parse(result.info.brandIds);
				let str=''
				$(parse).each(function (i,e) {
					str+='<option value="'+e.id+'">'+e.text+'</option>'
				})
				$("#brandId").html(str)
				let customAttributeItems = JSON.parse(result.info.customAttributeItems)
				str=''
				$(customAttributeItems).each(function (i,e) {
					str+='<div>'
					str+='  <div class="col-md-2 title">'+e.text+'</div>'
					str+='<div class="col-md-10 data">'
					str+=' <input class="form-control" value="'+e.text+'">'
					str+='</div>'
					str+='</div>'
				})
				$("#customAttributeDiv").html(str)
			})
		}
		function getSpec(typeId) {
			$.post("/specification/getSpecAndOptionsByTemplateId",{id:typeId},function (result) {
				let str='';
				$(result.data).each(function (i,e) {
					str+='<div>'
					str+='<div class="col-md-2 title">'+e.text+'</div>'
					str+='<div class="col-md-10 data">'
					$(e.options).each(function (index,em) {
						str+='<span>'
						str+='<input  type="checkbox" onclick="checkSpec(this,\''+e.text+'\',\''+em.optionName+'\')" >'+em.optionName
						str+='</span>'
					})
					str+='</div>'
					str+='</div>'
				})
				$("#dataType").html(str);
			})
		}
		var items = []
		function checkSpec(event,attributeName,attributeValue) {
			//便利数据判断用户勾选的规格名称是否已经存在
			var obj = searchAttributeName(items,"attributeName",attributeName);
			if (obj!=null){
				if ($(event).prop('checked')){
					obj.attributeValue.push(attributeValue);
				}else {
					obj.attributeValue.splice(obj.attributeValue.indexOf(attributeValue),1)
					if (obj.attributeValue.length<=0){
						items.splice(items.indexOf(obj),1)
					}
				}

			}else {
				items.push({"attributeName":attributeName,"attributeValue":[attributeValue]})
			}
			createSkUList();
		}
		function searchAttributeName(list,key,value) {
			for (var i = 0;i<list.length;i++){
				if(list[i][key] == value){
					return list[i]
				}
			}
			return null;
		}
		function createSkUList() {
			var itemList = [{spec:{}}];
			for (var i = 0;i<items.length;i++){
				itemList = addColum(itemList,items[i].attributeName,items[i].attributeValue);
			}
			specItemTh()
			specItemTbody(itemList);
		}
		function addColum(list,attributeName,attributeValues) {
			var newList = [];
			for (var i =0;i<list.length;i++){
				var oldRow = list[i]
				for (var j = 0;j<attributeValues.length;j++){
					var newRow = JSON.parse(JSON.stringify(oldRow))
					newRow.spec[attributeName] = attributeValues[j]
					newList.push(newRow)
				}
			}
			return newList;
		}
		
		
		//拼接th
		function specItemTh() {
			let str='<tr>'
			$(items).each(function (i,e) {
				str+=' <th class="sorting">'+e.attributeName+'</th>'
			})
			str+='<th class="sorting">价格</th><th class="sorting">库存</th><th class="sorting">是否启用</th><th class="sorting">是否默认</th>'
			$("#specItemTh").html(str)
		}
		//拼接tbody
		function specItemTbody(itemList) {
			let str='';
			$(itemList).each(function (i,e) {
				str+='<tr>'
				$(items).each(function (index,em) {

					let attributeName = em.attributeName;
					str+='<td>'+e.spec[attributeName]+'</td>'
				})
				str+='<td>'
				str+='<input class="form-control"  placeholder="价格">'
				str+='</td>'
				str+=' <td>'
				str+='<input class="form-control" placeholder="库存数量">'
				str+='</td>'
				str+=' <td>'
				str+='<input type="checkbox" >'
				str+='</td>'
				str+='<td>'
				str+='  <input type="checkbox" >'
				str+='</td>'
				str+='</tr>'
			})
			$("#specItemTbody").html(str)
		}
	</script>
    
</head>

<body class="hold-transition skin-red sidebar-mini" >

            <!-- 正文区域 -->
            <section class="content">

                <div class="box-body">

                    <!--tab页-->
                    <div class="nav-tabs-custom">

                        <!--tab头-->
                        <ul class="nav nav-tabs">                       		
                            <li class="active">
                                <a href="#home" data-toggle="tab">商品基本信息</a>
                            </li>   
                            <li >
                                <a href="#pic_upload" data-toggle="tab">商品图片</a>                                                        
                            </li>    
                            <li >
                                <a href="#customAttribute" data-toggle="tab">扩展属性</a>                                                        
                            </li>     
                            <li >
                                <a href="#spec" data-toggle="tab" >规格</a>                                                        
                            </li>                       
                        </ul>
                        <!--tab头/-->
						
                        <!--tab内容-->
                        <div class="tab-content">

                            <!--表单内容-->
                            <div class="tab-pane active" id="home">
                                <div class="row data-type">                                  
								   <div class="col-md-2 title">商品分类</div>
									<form id="insertFrom">
		                           	  <div class="col-md-10 data">

		                           	  	<table>
		                           	  		<tr>
		                           	  			<td>
		                           	  				<select class="form-control" id="category1Id" name="category1Id" onchange="listItemCat2(this.value)">
														<option>请选择</option>
													</select>
		                              			</td>
		                              			<td>
		                           	  				<select class="form-control select-sm" id="category2Id" name="category2Id" onchange="listItemCat3(this.value)">
														<option>请选择</option>
													</select>
		                              			</td>
		                              			<td>
		                           	  				<select class="form-control select-sm" id="category3Id" name="category3Id" onchange="getType(this.value)">
														<option>请选择</option>
													</select>
		                              			</td>
		                              			<td id="typeId">

		                              			</td>
		                           	  		</tr>
		                           	  	</table>
		                              	
		                              </div>	                              
		                          	  
									
		                           <div class="col-md-2 title">商品名称</div>
		                           <div class="col-md-10 data">
		                               <input type="text" class="form-control" name="goodsName"  id="goodsName" placeholder="商品名称" value="">
		                           </div>
		                           
		                           <div class="col-md-2 title">品牌</div>
		                           <div class="col-md-10 data">
		                              <select class="form-control" name="brandId" id="brandId"></select>
		                           </div>
		
								   <div class="col-md-2 title">副标题</div>
		                           <div class="col-md-10 data">
		                               <input type="text" class="form-control" name="caption" id="caption" placeholder="副标题" value="">
		                           </div>
		                           
		                           <div class="col-md-2 title">价格</div>
		                           <div class="col-md-10 data">
		                           	   <div class="input-group">
			                          	   <span class="input-group-addon">¥</span>
			                               <input type="text" class="form-control"  placeholder="价格" value="" id="price" name="price">
		                           	   </div>
		                           </div>
		                           
		                           <div class="col-md-2 title editer">商品介绍</div>
                                   <div class="col-md-10 data editer">
                                       <textarea id="content" style="width:800px;height:400px;visibility:hidden;" ></textarea>
                                   </div>
		                           
		                           <div class="col-md-2 title rowHeight2x">包装列表</div>
		                           <div class="col-md-10 data rowHeight2x">
		                               
		                           	<textarea rows="4"  class="form-control"   placeholder="包装列表" id="packageList" name="packageList"></textarea>
		                           </div>
		                           
		                           <div class="col-md-2 title rowHeight2x">售后服务</div>
		                           <div class="col-md-10 data rowHeight2x">
		                               <textarea rows="4"  class="form-control"    placeholder="售后服务" id="saleService" name="saleService"></textarea>
		                           </div>
									</form>
                                    
                                </div>
                            </div>
                            
                            <!--图片上传-->
                            <div class="tab-pane" id="pic_upload">
                                <div class="row data-type">                                  
								 <!-- 颜色图片 -->
								 <div class="btn-group">
					                 <button type="button" class="btn btn-default" title="新建" data-target="#uploadModal"  data-toggle="modal" onclick="insert()"  ><i class="fa fa-file-o"></i> 新建</button>
                             		                 
					             </div>
								 
								 <table class="table table-bordered table-striped table-hover dataTable">
					                    <thead>
					                        <tr>
					                            
											    <th class="sorting">颜色</th>
											    <th class="sorting">图片</th>
												<th class="sorting">操作</th>
							            </thead>
					                    <tbody id="insertImgTbody">
					                      <!--<tr id="insertImgTr">
									            &lt;!&ndash;<td>
									            	
									            </td>
									            <td>
									           		<img alt="" src="" width="100px" height="100px">
									            </td>
												 <td> <button type="button" class="btn btn-default" title="删除" ><i class="fa fa-trash-o"></i> 删除</button></td> &ndash;&gt;
					                      </tr>-->
					                    </tbody>
								 </table> 
								  
                                </div>
                            </div>
                           
                           
                            <!--扩展属性-->
                            <div class="tab-pane" id="customAttribute">
                                <div class="row data-type" id="customAttributeDiv">
	                                <!--<div>
		                                <div class="col-md-2 title">扩展属性1</div>
				                        <div class="col-md-10 data">
				                              <input class="form-control" placeholder="扩展属性1">	            	 
				                        </div>
	                                </div>       
									<div>
		                                <div class="col-md-2 title">扩展属性2</div>
				                        <div class="col-md-10 data">
				                              <input class="form-control" placeholder="扩展属性2">	            	 
				                        </div>
	                                </div>  -->
                                </div>
                            </div>
                      
                            <!--规格-->
                            <div class="tab-pane" id="spec">
                            	<div class="row data-type">
	                            	<div class="col-md-2 title">是否启用规格</div>
			                        <div class="col-md-10 data">
			                        	<input type="checkbox" >			                           
			                        </div>
                            	</div>
                            	<p>
                            	
                            	<div>
                            	
	                                <div class="row data-type" id="dataType">
	                                
		                                <!--<div>
			                                <div class="col-md-2 title">屏幕尺寸</div>
					                        <div class="col-md-10 data">
					                               
					                            <span>
					                            	<input  type="checkbox" >4.0					                            				                            	
					                            </span>  	
												<span>
					                            	<input  type="checkbox" >4.5					                            				                            	
					                            </span>
												<span>
					                            	<input  type="checkbox" >5.0					                            				                            	
					                            </span>												
					                            	
					                        </div>
		                                </div>   
										<div>
			                                <div class="col-md-2 title">网络制式</div>
					                        <div class="col-md-10 data">
					                               
					                            <span>
					                            	<input  type="checkbox" >2G					                            				                            	
					                            </span>  	
												<span>
					                            	<input  type="checkbox" >3G					                            				                            	
					                            </span>
												<span>
					                            	<input  type="checkbox" >4G					                            				                            	
					                            </span>												
					                            	
					                        </div>
		                                </div>  -->
		                                                                                  
	                                </div>
	
	                                
	                                <div class="row data-type">
	                                	 <table class="table table-bordered table-striped table-hover dataTable">
						                    <thead id="specItemTh">
						                        <!--<tr>
												    <th class="sorting">屏幕尺寸</th>
													<th class="sorting">网络制式</th>
												    <th class="sorting">价格</th>
												    <th class="sorting">库存</th>
												    <th class="sorting">是否启用</th>
												    <th class="sorting">是否默认</th>
											    </tr>-->
								            </thead>
						                    <tbody id="specItemTbody">
						                     <!-- <tr>
										            <td>
										            	4.0
										            </td>
													<td>
										            	3G
										            </td>
										            <td>
										           		<input class="form-control"  placeholder="价格">
										            </td>
										            <td>
										            	<input class="form-control" placeholder="库存数量">
										            </td>
										            <td>
										             	<input type="checkbox" >
										            </td>
										            <td>
										                <input type="checkbox" >									             	
										            </td>
						                      </tr>
											  <tr>					                           
										            <td>
										            	4.0
										            </td>
													<td>
										            	4G
										            </td>
										            <td>
										           		<input class="form-control"  placeholder="价格">
										            </td>
										            <td>
										            	<input class="form-control" placeholder="库存数量">
										            </td>
										            <td>
										             	<input type="checkbox" >
										            </td>
										            <td>
										                <input type="checkbox" >									             	
										            </td>
						                      </tr>
											  <tr>					                           
													<td>
										            	5.0
										            </td>
													<td>
										            	3G
										            </td>
										            <td>
										           		<input class="form-control"  placeholder="价格">
										            </td>
										            <td>
										            	<input class="form-control" placeholder="库存数量">
										            </td>
										            <td>
										             	<input type="checkbox" >
										            </td>
										            <td>
										                <input type="checkbox" >									             	
										            </td>
						                      </tr>
											  <tr>					                           
													<td>
										            	5.0
										            </td>
													<td>
										            	4G
										            </td>
										            <td>
										           		<input class="form-control"  placeholder="价格">
										            </td>
										            <td>
										            	<input class="form-control" placeholder="库存数量">
										            </td>
										            <td>
										             	<input type="checkbox" >
										            </td>
										            <td>
										                <input type="checkbox" >									             	
										            </td>
						                      </tr>-->
											  
						                    </tbody>
									 	</table>
								
	                                </div>
	                                
	                            </div>
                            </div>
                            
                        </div>
                        <!--tab内容/-->
						<!--表单内容/-->
							 
                    </div>
                 	
                 	
                 	
                 	
                   </div>
                  <div class="btn-toolbar list-toolbar">
				      <button class="btn btn-primary" onclick="volidate()"><i class="fa fa-save" ></i>保存</button>
				      <button class="btn btn-default" >返回列表</button>
				  </div>
			
            </section>
            
            
<!-- 上传窗口 -->
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" >
	<div class="modal-content">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
			<h3 id="myModalLabel">上传商品图片</h3>
		</div>
		<div class="modal-body">							
			
			<table class="table table-bordered table-striped">
		      	<tr>
		      		<td>颜色</td>
		      		<td><input  class="form-control" placeholder="颜色" id="color" name="color">  </td>
		      	</tr>			    
		      	<tr>
		      		<td>商品图片</td>
		      		<td>
						<table>
							<tr>
								<td>
									<input type="file"class="form-control" name="images" id="images">
									<input type="hidden" name="img" id="img">
								</td>
							</tr>						
						</table>
		      		</td>
		      	</tr>		      	
			 </table>				
			
		</div>
		<div class="modal-footer">						
			<button class="btn btn-success"  data-dismiss="modal" aria-hidden="true" onclick="insertImg()">保存</button>
			<button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button>
		</div>
	  </div>
	</div>
</div>

            
            <!-- 正文区域 /-->
<script type="text/javascript">

	var editor;
	KindEditor.ready(function(K) {
		editor = K.create('textarea[id="content"]', {
			allowFileManager : true
		});
	});
	//添加
	function volidate() {
		editor.sync();
		var introduction =$.trim( $("#content").val());
		let itemImage = [];
		const trs = $("#insertImgTbody tr")
		for(let i=0; i<trs.length; i++){
			const tds = $(trs[i]).find("td");
			const color = $(tds[0]).find("input").val();
			const img = $(tds[1]).find("input").val();
			const custom = {"color":color,"img":img};
			itemImage.push(custom);//对象js 对象 java不好接受，把对象转成json字符串，后台java转成list集合
			 }
			let itemImages = JSON.stringify(itemImage);
		let customAttributeItem = [];
		const divs = $("#customAttributeDiv").children("div")
		for(let i=0; i<divs.length; i++){
			const tds = $(divs[i]).find("div");
			const text = $(tds[0]).html();
			const value = $(tds[1]).find("input").val();
			const custom = {"text":text,"value":value};
			customAttributeItem.push(custom);//对象js 对象 java不好接受，把对象转成json字符串，后台java转成list集合
		}
		let customAttributeItems = JSON.stringify(customAttributeItem);


		//[{spec:{attributeName:attributeValue}},price:{price},xxx:{xxx},{spec:{attributeName:attributeValue}},price:{price},xxx:{xxx}] ListMap(String,Object))
		let products = [];  //   List prifucts = new Arrayslist();
		const tobody = $("#specItemTbody tr")
		for(let i=0; i<tobody.length; i++){
			let product = {spec:{}} //
			//console.log(item);
			const tds = $(tobody[i]).find("td"); //
			let tdCount;
			$(items).each(function (index,e) {
				const attributeValue = $(tds[index]).text();
				product.spec[e.attributeName] = attributeValue //product.spec    {key}
				tdCount = index
			})

			product["price"] = $(tds[tdCount+1]).find("input").val();//product.put("price",value)
			const num = $(tds[tdCount+2]).find("input").val();
			product["num"] = num // product.put(key,value) //key "num" value num
			const status = $(tds[tdCount+3]).find("input");
			if ($(status).prop("checked")){
				product["status"] = 1
			}else {
				product["status"] = 2
			}
			const isDefault = $(tds[tdCount+4]).find("input");
			if ($(isDefault).prop("checked")){
				product["isDefault"] = 1
			}else {
				product["isDefault"] = 0
			}
			products.push(product)
		}
		products = JSON.stringify(products)
		console.log(products)
		let specificationItems = JSON.stringify(items)
		$.post("/goods/insertGoods",$("#insertFrom").serialize()+"&introduction="+introduction+"&customAttributeItems="+customAttributeItems+"&itemImages="+itemImages+"&specificationItems="+specificationItems+"&products="+products,function (result) {
			if (result.code==200){
				alert("添加成功")
				window.location.reload();
			}
		})
	}
</script>

</body>
<%--bootstrap-fileinput--%>
<link rel="stylesheet" type="text/css" href="/bootstrap-fileinput/css/fileinput.css">
<script type="text/javascript" src="/bootstrap-fileinput/js/fileinput.js"></script>
<script type="text/javascript" src="/bootstrap-fileinput/js/locales/zh.js"></script>
<script>
	$(function(){
		$('#images').fileinput({
					language: 'zh',//语言：中文
					uploadUrl: "/goodsImg/upload", //上传地址
					browseClass: 'btn btn-primary', //按钮样式
					maxFileCount: 1,//最多支持上传的个数
					enctype: 'multipart/form-data',//序列化
					maxFileSize: 1024, //单位为kb, 如果为0表示不限制文件大小
					allowedFileExtensions: ['jpg', 'gif', 'png'],//限制上传文件的类型
			});
		$("#images").on("fileuploaded", function(event, data, previewId, index){
			console.log(data);
			if(data.response){
				$("#img").val(data.response.info)
			}
		})
	})
	//清除图片
	function insert() {
		$("#color").val("");
		$("#img").val("");
		$(".fileinput-remove-button").click();
	}
	//添加拼接图片
	function insertImg() {

		let color = $("#color").val();
		let img = $("#img").val()
		let str = '<tr>'
		str += '<td>'+color+'<input type="hidden" name="colors" value="'+color+'"></td>'
		str+='<td>'
		str+='<img alt="" src="'+img+'" width="100px" height="100px"><input type="hidden" name="imgs" value="'+img+'">'
		str+='</td>'
		str+='</td>'
		str+='<td> <button type="button" class="btn btn-default" title="删除" onclick="deleteNode(this)"><i class="fa fa-trash-o"></i> 删除</button></td></tr>'
		$("#insertImgTbody").append(str)
	}
	//添加规格方法页面 删除规格选项
	function deleteNode(obj) {
		if(confirm("确定要删除么")){
			document.getElementById("insertImgTbody").removeChild(obj.parentNode.parentNode);
		}
	}
</script>
</html>